package com.lantzuc.lanucbackend.controller;

import com.lantzuc.lanucbackend.common.BaseResponse;
import com.lantzuc.lanucbackend.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * <p>Project: lanuc-backend
 * <p>Powered by Lantz On 2025/10/12
 *
 * @author Lantz
 * @version 1.0
 * @Description sessionController
 * @since 1.8
 */
@Slf4j
@RestController
public class SessionController {

    // 设置 Cookie
    @GetMapping("/c1")
    public BaseResponse cookie1(HttpServletResponse response) {
        response.addCookie(new Cookie("loginUser", "lantz"));
        return ResultUtils.success("ok");
    }

    // 获取 Cookie
    @GetMapping("/c2")
    public BaseResponse cookie2(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("loginUser")) {
                log.info("loginUser value=" + cookie.getValue());
            }
        }
        return ResultUtils.success("ok");
    }

    // 设置 Session
    @GetMapping("/s1")
    public BaseResponse session1(HttpSession session) {
        log.info("HttpSession-s1: {}", session.hashCode());
        session.setAttribute("loginUser", "lantz");
        return ResultUtils.success("ok");
    }

    // 获取 Session
    @GetMapping("/s2")
    public BaseResponse session2(HttpServletRequest request) {
        HttpSession session = request.getSession();
        log.info("HttpSession-s2: {}", session.hashCode());
        Object loginUser = session.getAttribute("loginUser");
        log.info("loginUser: {}", loginUser);
        return ResultUtils.success("ok");
    }

}














